package com.ht.web360.UserServer.controller;

import cn.hutool.core.util.StrUtil;
import com.ht.web360.UserServer.dao.UserInfo;
import com.ht.web360.UserServer.service.UserInfoService;
import com.ht.web360.base.dto.RPage;
import com.ht.web360.base.dto.Res;
import com.ht.web360.base.dto.UserInfo.dto.UserInfoDto;
import com.ht.web360.base.dto.UserInfo.vo.UserLoginVo;
import com.ht.web360.base.enums.UserType;
import com.ht.web360.base.utils.TokenUtil;
import com.ht.web360.base.utils.exceptions.MessageException;
import com.ht.web360.base.utils.interfaces.RequireUserType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name = "用户信息控制器")
public class UserInfoController {
    private final UserInfoService userInfoService;

    public UserInfoController(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @Operation(summary = "获取自身数据")
    @GetMapping
    @RequireUserType(UserType.User)
    public Res<UserInfoDto> getSelf(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String token = null;
        for (var cookie : cookies) {
            if ("token".equals(cookie.getName())) {
                token = cookie.getValue();
            }
        }
        if (StrUtil.isBlankIfStr(token)) {
            return Res.fail("用户未登录");
        }
        UserInfoDto user = TokenUtil.getUser(token);
        if (user == null || StrUtil.isBlankIfStr(user.getId())) {
            return Res.fail("用户未登录");
        }
        return Res.ok(userInfoService.getById(user.getId()));
    }

    @Operation(summary = "通过id获取用户")
    @GetMapping("/{id}")
    @RequireUserType(UserType.Public)
    public Res<UserInfoDto> getUserInfoById(@PathVariable(value = "id") Long id) {
        if (id == null) {
            throw new MessageException("请求参数为空");
        }
        UserInfoDto userInfoDto = userInfoService.getById(id);
        return Res.ok(userInfoDto);
    }

    @Operation(summary = "分页获取用户信息")
    @GetMapping("/page")
    @RequireUserType(UserType.Admin)
    public Res<RPage<UserInfoDto>> pageUser(
            @RequestParam(value = "current", required = false, defaultValue = "1") long current,
            @RequestParam(value = "size", required = false, defaultValue = "10") long size
    ) {
        RPage<UserInfoDto> page = userInfoService.pageUserInfo(current, size);
        return Res.ok(page);
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    @RequireUserType(UserType.Public)
    public Res<Void> login(
            @RequestBody UserLoginVo userLogin,
            HttpServletResponse response
    ) {
        String token = userInfoService.login(userLogin);
        setCookie(token, response);
        return Res.ok();
    }

    @Operation(summary = "创建用户",
            responses = @ApiResponse(description = "用户id"))
    @PostMapping("/create")
    @RequireUserType(UserType.Public)
    public Res<Long> create(@RequestBody UserInfo userInfo) {
        long id = userInfoService.save(userInfo);
        return Res.ok(id);
    }

    @Operation(summary = "更新用户数据")
    @PostMapping("/update")
    @RequireUserType(UserType.User)
    public Res<Void> updateUser(@RequestBody UserInfoDto userInfoDto,
                                HttpServletResponse response) {
        String token = userInfoService.updateById(userInfoDto);
        setCookie(token, response);
        return Res.ok();
    }

    @Operation(summary = "更新头像")
    @PostMapping("/update/avatar")
    @RequireUserType(UserType.User)
    public Res<Void> updateAvatar(MultipartFile file, HttpServletResponse response) {
        String token = userInfoService.updateAvatar(file);
        setCookie(token, response);
        return Res.ok();
    }

    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    @RequireUserType(UserType.User)
    public Res<Void> logout(HttpServletResponse response) {
        setCookie(null, response);
        return Res.ok();
    }

    private void setCookie(String token, HttpServletResponse response) {
        Cookie cookie = new Cookie("token", token);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(7 * 24 * 60 * 60);
        response.addCookie(cookie);
    }
}
